package com.topstack.aspro.biz

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.widget.Toast
import com.alibaba.android.arouter.facade.annotation.Route
import com.topstack.aspro.databinding.ActivityRegisterBinding
import com.topstack.common.http.ApiFactory
import com.topstack.common.http.api.AccountApi
import com.topstack.common.ui.component.HiBaseActivity
import com.topstack.hilibrary.restful.HiCallback
import com.topstack.hilibrary.restful.HiResponse

@Route(path = "/account/registration")
class RegistrationActivity : HiBaseActivity() {
    private lateinit var binding: ActivityRegisterBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityRegisterBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.actionBack.setOnClickListener { onBackPressed() }
        binding.actionSubmit.setOnClickListener { submit() }
    }

    private fun submit() {
        val orderId = binding.inputItemOrderId.getEditText().text.toString()
        val moocId = binding.inputItemMoocId.getEditText().text.toString()
        val username = binding.inputItemUsername.getEditText().text.toString()
        val pwd = binding.inputItemPwd.getEditText().text.toString()
        val pwdSec = binding.inputItemPwdCheck.getEditText().text.toString()

        if (TextUtils.isEmpty(orderId) or (TextUtils.isEmpty(moocId)) or (TextUtils.isEmpty(username)) or (TextUtils.isEmpty(
                pwd
            )) or (!TextUtils.equals(pwd, pwdSec))
        ) {
            return
        }

        ApiFactory.create(AccountApi::class.java).register(username, pwd, moocId, orderId)
            .enqueue(object : HiCallback<String> {
                override fun onSuccess(response: HiResponse<String>) {
                    if (response.code == HiResponse.SUCCESS) {
                        val intent = Intent()
                        intent.putExtra("username", username)
                        setResult(Activity.RESULT_OK, intent)
                        finish()
                    } else {
                        showToast(response.msg!!)
                    }
                }

                override fun onFailed(throwable: Throwable) {
                    showToast(throwable.message!!)
                }

            })

    }

    private fun showToast(message: String) {
        Toast.makeText(applicationContext, message, Toast.LENGTH_SHORT).show()
    }
}